package com.mt.repair.service.repairManagement.impl;

import com.mt.repair.dao.repairManagement.RepairOrderStatusRecordDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.repair.entity.repairManagement.RepairOrderStatusRecord;
import com.mt.repair.service.repairManagement.RepairOrderStatusRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class RepairOrderStatusRecordServiceBean extends BaseService implements RepairOrderStatusRecordService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private RepairOrderStatusRecordDao repairOrderStatusRecordDao;

	@Resource
	private RedisTemplate<String, List<RepairOrderStatusRecord>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询维修单状态记录集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findRepairOrderStatusRecords(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindRepairOrderStatusRecords(pageDTO);
		List<RepairOrderStatusRecord> repairOrderStatusRecordDTOS = this.repairOrderStatusRecordDao.findRepairOrderStatusRecords(pageDTO);
		Long totalCount = this.repairOrderStatusRecordDao.findRepairOrderStatusRecordTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(repairOrderStatusRecordDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部维修单状态记录集合
	 *
	 */
	@Override
	public List<RepairOrderStatusRecord> findAllRepairOrderStatusRecords(){
		return this.repairOrderStatusRecordDao.findAllRepairOrderStatusRecords();
	}

	/**
	 * 查询所有维修单状态记录集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<RepairOrderStatusRecord> findAllRepairOrderStatusRecordsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllRepairOrderStatusRecordsWithIdName();
		return this.repairOrderStatusRecordDao.findAllRepairOrderStatusRecordsWithIdName();
	}

	/**
	 * 根据名称查询维修单状态记录集合(只提取ID 和 Name)
	 *
	 * @param repairOrderStatusRecordName 名称
	 */
	@Override
	public List<RepairOrderStatusRecord> findRepairOrderStatusRecordsWithIdNameByName(String repairOrderStatusRecordName){
		//TODO:请在此校验参数的合法性
		this.validateFindRepairOrderStatusRecordsWithIdNameByName(repairOrderStatusRecordName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:RepairOrderStatusRecord_where_repairOrderStatusRecordName_" + repairOrderStatusRecordName);
		List<RepairOrderStatusRecord> repairOrderStatusRecords = new ArrayList<>();
		if (keys.isEmpty()) {
		repairOrderStatusRecords = this.repairOrderStatusRecordDao.findRepairOrderStatusRecordsWithIdNameByName(repairOrderStatusRecordName);
		redisTemplate.opsForValue().set("searchData:RepairOrderStatusRecord_where_repairOrderStatusRecordName_" + repairOrderStatusRecordName, repairOrderStatusRecords, 30, TimeUnit.DAYS);
		} else {
		repairOrderStatusRecords = redisTemplate.opsForValue().get("searchData:RepairOrderStatusRecord_where_repairOrderStatusRecordName_" + repairOrderStatusRecordName);
		}
		return repairOrderStatusRecords;
	}

	/**
	 * 根据ID查询指定的维修单状态记录(只提取ID 和 Name)
	 *
	 * @param repairOrderStatusRecordId Id
	 */
	@Override
	public RepairOrderStatusRecord findRepairOrderStatusRecordsWithIdNameById(Long repairOrderStatusRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindRepairOrderStatusRecordsWithIdNameById(repairOrderStatusRecordId);
		return this.repairOrderStatusRecordDao.findRepairOrderStatusRecordsWithIdNameById(repairOrderStatusRecordId);
	}

	/**
	 * 根据ID查询指定的维修单状态记录
	 *
	 * @param repairOrderStatusRecordId Id
	 */
	@Override
	public RepairOrderStatusRecord findRepairOrderStatusRecord(Long repairOrderStatusRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindRepairOrderStatusRecord(repairOrderStatusRecordId);
		return this.repairOrderStatusRecordDao.findRepairOrderStatusRecord(repairOrderStatusRecordId);
	}

	/**
	 * 根据ID查询指定的维修单状态记录(包含外键)
	 *
	 * @param repairOrderStatusRecordId Id
	 */
	@Override
	public RepairOrderStatusRecord findRepairOrderStatusRecordWithForeignName(Long repairOrderStatusRecordId){
		//TODO:请在此校验参数的合法性
		this.validateFindRepairOrderStatusRecordWithForeignName(repairOrderStatusRecordId);
		return this.repairOrderStatusRecordDao.findRepairOrderStatusRecordWithForeignName(repairOrderStatusRecordId);
	}

	/**
	 * 新增维修单状态记录
	 *
	 * @param repairOrderStatusRecord 实体对象
	 */
	@Override
	public RepairOrderStatusRecord saveRepairOrderStatusRecord(RepairOrderStatusRecord repairOrderStatusRecord){
		//TODO:请在此校验参数的合法性
		this.validateSaveRepairOrderStatusRecord(repairOrderStatusRecord);
		//TODO:填充公共参数
		repairOrderStatusRecord.setCreatorId(this.getLoginUserId());
		repairOrderStatusRecord.setCreateDatetime(new Date());
		repairOrderStatusRecord.setCreatorName(this.getLoginUser()!=null?this.getLoginUser().getNickname():"系统");

		Long rows = this.repairOrderStatusRecordDao.saveRepairOrderStatusRecord(repairOrderStatusRecord);
		if(rows != 1)
		{
			String error = "新增保存维修单状态记录出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return repairOrderStatusRecord;
	}

	/**
	 * 更新维修单状态记录
	 *
	 * @param repairOrderStatusRecord 实体对象
	 */
	@Override
	public RepairOrderStatusRecord updateRepairOrderStatusRecord(RepairOrderStatusRecord repairOrderStatusRecord){
		//TODO:请在此校验参数的合法性
		this.validateUpdateRepairOrderStatusRecord(repairOrderStatusRecord);
		Long rows = this.repairOrderStatusRecordDao.updateRepairOrderStatusRecord(repairOrderStatusRecord);
		if(rows != 1)
		{
			String error = "修改保存维修单状态记录出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return repairOrderStatusRecord;
	}

	/**
	 * 根据ID删除维修单状态记录
	 *
	 * @param repairOrderStatusRecordId ID
	 */
	@Override
	public void deleteRepairOrderStatusRecord(Long repairOrderStatusRecordId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteRepairOrderStatusRecord(repairOrderStatusRecordId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(RepairOrderStatusRecord.class, repairOrderStatusRecordId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.repairOrderStatusRecordDao.deleteRepairOrderStatusRecord(repairOrderStatusRecordId);
		if(rows != 1){
			String error = "删除维修单状态记录出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindRepairOrderStatusRecords(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateFindRepairOrderStatusRecordsWithIdNameByName(String repairOrderStatusRecordName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}


	private void validateFindAllRepairOrderStatusRecordsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateFindRepairOrderStatusRecordsWithIdNameById(Long repairOrderStatusRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateFindRepairOrderStatusRecord(Long repairOrderStatusRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateFindRepairOrderStatusRecordWithForeignName(Long repairOrderStatusRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateSaveRepairOrderStatusRecord(RepairOrderStatusRecord repairOrderStatusRecord) {
	//不为空判断
	if (repairOrderStatusRecord.getEid() != null || repairOrderStatusRecord.getCreatorId() != null || repairOrderStatusRecord.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateUpdateRepairOrderStatusRecord(RepairOrderStatusRecord repairOrderStatusRecord) {
	//不为空判断
	if (repairOrderStatusRecord.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.repairOrderStatusRecordDao.findRepairOrderStatusRecordTotalCount(PageDTO.create(RepairOrderStatusRecord.FIELD_ID, repairOrderStatusRecord.getEid())) == 0) {
	throw new BusinessException("修改的维修单状态记录 " + repairOrderStatusRecord.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	private void validateDeleteRepairOrderStatusRecord(Long repairOrderStatusRecordId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateRepairOrderStatusRecord()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
